<?php
//定时发放分红
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;


class Bonus extends Command
{
    protected function configure()
    {
        $this->setName('bonus');
    }

    protected function execute(Input $input, Output $output)
    {
        
        try{
            $bonus_type=db('config')->where(['name'=>'bonus_type'])->value('value');
            $price_low_partner=db('config')->where(['name'=>'price_low_partner'])->value('value');
            $price_low_store=db('config')->where(['name'=>'price_low_store'])->value('value');
            $price_low_center=db('config')->where(['name'=>'price_low_center'])->value('value');
            $day=date('d');
            $month=date('m');
            $isbon=0;
            $isbon=1;//后期需注释
            // var_dump($bonus_type);
            // if($bonus_type==1)
            // {
            //     //半月
            //     if($day==2 || $day==11)
            //     {
            //         //生成
            //         $isbon=1;
            //     } 
            // }
            // if($bonus_type==2)
            // {
            //     //一个月
            //     if($day==2)
            //     {
            //         //生成
            //         $isbon=1;
            //     } 
            // }
            // if($bonus_type==3)
            // {
            //     //季度
            //     if($day==2&& ($month==1 || $month==4 || $month==7 || $month==10))
            //     {
            //         //生成
            //         $isbon=1;
            //     } 
            // }
            $insertdata=[];
            $storedata=[];
            // var_dump($isbon);
            if($isbon==1)
            {
                //生成
                $where='';
                $bonusinfo=db('bonus_log')->order('id desc')->find();
                $time=strtotime(date('Y-m-d 23:59:59', strtotime('-1 day')));
                //分红比例
                $center_rate=db('config')->where('name','center_rate')->value('value');
                $store_rate=db('config')->where('name','store_rate')->value('value');
                $partner_rate=db('config')->where('name','partner_rate')->value('value');

                $where_pt='';
                $where_tui_pt='';
                $where_salesman_pt='';
                $where_store='';
                $where_tui_store='';
                $where_fx='';
                if($bonusinfo)
                {
                    $starttime=$bonusinfo['endtime'];
                    $endtime=$time;
                    $where=" and  order.order_qr_time between ".$bonusinfo['endtime']." and ".$time;
                    $where_pt=" and  fa_time between ".$bonusinfo['endtime']." and ".$time;
                    $where_tui_pt=" and  addtime between ".$bonusinfo['endtime']." and ".$time;
                    $where_salesman_pt=" and  addtime between ".$bonusinfo['endtime']." and ".$time;

                    $where_store=" and  successtime between ".$bonusinfo['endtime']." and ".$time;
                    $where_tui_store=" and  addtime between ".$bonusinfo['endtime']." and ".$time;
                    $where_fx=" and  addtime between ".$bonusinfo['endtime']." and ".$time;
                    
                }
                else
                {
                    $starttime='';
                    $endtime=$time;
                    $where=" and  order.order_qr_time<=".$time;
                    $where_pt=" and  fa_time<=".$time;
                    $where_tui_pt=" and  addtime<=".$time;
                    $where_salesman_pt=" and  addtime<=".$time;

                    $where_store=" and  successtime<=".$time;//计算空间中心的销售利润，按用户卖出完成时间算
                    $where_tui_store=" and  addtime<=".$time;
                    $where_fx=" and  addtime<=".$time;
                }

                

                //查询中心
                $centersql="SELECT store.*, SUM(`order`.price) AS total_spent 
                FROM jianji_store AS store 
                JOIN jianji_order AS `order` ON store.id = `order`.store_id 
                WHERE `order`.order_type in ('1','2','3') AND store.type = '1' AND store.is_bonus = 1".$where."
                GROUP BY store.id 
                HAVING SUM(`order`.price) >= ".$price_low_center;
                $centerlist=Db::Query($centersql);
                $centercount=count($centerlist);
                foreach ($centerlist as $key => $value) {
                    # code...
                    
                    //如果是中心
                    if($value['type']=='1')
                    {
                        //中心，计算平台的利润
                        //平台利润=平台的销售利润-推广的钱-业务员的提成
                        $xiaoshou_price=db('order_goods_store')->where($where_pt)->sum('goods_price-cost_price');
                        $tui_price=db('promition_log')->where('store_id',0)->where($where_tui_pt)->where('user_del','0')->sum('price');
                        $salesman_price=db('salesman_log')->where($where_salesman_pt)->sum('price');
                        $lirun_pt=$xiaoshou_price-$tui_price-$salesman_price;
                        $price=$lirun_pt*$center_rate/$centercount*$value['fh_rate'];
                        //添加分红订单
                    
                        $data['ordernum']='';
                        $data['promotion_type']='3';
                        $data['promotion_id']=$value['id'];
                        $data['to_store_id']=0;
                        $data['start_time']=$starttime;
                        $data['end_time']=$endtime;
                        $data['lirun']=$lirun_pt;
                        $data['rate']=$value['fh_rate'];
                        $data['price']=$price;
                        $data['count']=$centercount;
                        $data['addtime']=time();
                        $data['bonus_type']=$bonus_type;
                        $data['remark']=$value['fh_remark'];
                        $insertdata[]=$data;
                        $storedata[$value['id']]=$price;

                    }
                }
                //查询空间
                $storesql="SELECT store.*, SUM(`order`.price) AS total_spent 
                FROM jianji_store AS store 
                JOIN jianji_order AS `order` ON store.id = `order`.store_id 
                WHERE `order`.order_type  in ('1','2','3') AND store.type = '2' AND store.is_bonus = 1".$where."
                GROUP BY store.id 
                HAVING SUM(`order`.price) > = ".$price_low_store;
                $storelist=Db::Query($storesql);
                $storecount=count($storelist);
                foreach ($storelist as $key => $value) {
                    # code...
                    if($value['type']=='2')
                    {
                        //生成分红订单，查询所属中心的利润
                        //中心的利润=销售利润-推广的钱-分销的钱+分红的钱
                        $xiaoshou_price=db('order_goods_store')->where('store_id',$value['pid'])->where($where_store)->sum('goods_price-cost_price');
                        $tui_price=db('promition_log')->where('store_id',$value['pid'])->where($where_tui_store)->where('user_del','0')->sum('price');
                        $fx_price=db('fenxiao_log')->where($where_fx)->where('store_id',$value['pid'])->where('user_del','0')->sum('price');
                        $bonus_price=isset($storedata[$value['pid']])?$storedata[$value['pid']]:0;
                        $lirun_pt=$xiaoshou_price-$tui_price-$fx_price+$bonus_price;
                        $price=$lirun_pt*$store_rate/$storecount*$value['fh_rate'];
                        //添加分红订单
                    
                        $data['ordernum']='';
                        $data['promotion_type']='2';//分红人角色:1=合伙人,2=空间,3=中心
                        $data['promotion_id']=$value['id'];
                        $data['to_store_id']=$value['pid'];
                        $data['start_time']=$starttime;
                        $data['end_time']=$endtime;
                        $data['lirun']=$lirun_pt;
                        $data['rate']=$value['fh_rate'];
                        $data['price']=$price;
                        $data['count']=$storecount;
                        $data['addtime']=time();
                        $data['bonus_type']=$bonus_type;
                        $data['remark']=$value['fh_remark'];
                        $insertdata[]=$data;
                        $storedata[$value['id']]=$price;

                    }
                    
                }


                //查询可发放分红的合伙人，销售额达到多少，有分红权
                $usersql="SELECT user.id, user.username, SUM(`order`.price) AS total_spent 
                FROM jianji_user AS user 
                JOIN jianji_order AS `order` ON user.id = `order`.user_id 
                WHERE `order`.order_type = '3' AND user.type = '3' AND user.is_bonus = 1".$where."
                GROUP BY user.id
                HAVING SUM(`order`.price) >= ".$price_low_partner;
                $userlist=Db::Query($usersql);
                $usercount=count($userlist);
                // var_dump($userlist);
                foreach ($userlist as $key => $value) {
                    # code...
                    //生成分红订单，查询所属空间中心的利润
                    //空间的利润=销售利润-推广的钱-分销的钱+分红的钱

                    $xiaoshou_price=db('order_goods_store')->where('store_id',$value['store_id'])->where($where_store)->sum('goods_price-cost_price');
                    $tui_price=db('promition_log')->where('store_id',$value['store_id'])->where($where_tui_store)->where('user_del','0')->sum('price');
                    $fx_price=db('fenxiao_log')->where($where_fx)->where('store_id',$value['store_id'])->where('user_del','0')->sum('price');
                    $bonus_price=isset($storedata[$value['pid']])?$storedata[$value['pid']]:0;
                    $lirun_pt=$xiaoshou_price-$tui_price-$fx_price+$bonus_price;
                    $price=$lirun_pt*$partner_rate/$usercount*$value['fh_rate'];
                    //添加分红订单
                    
                    $data['ordernum']='';
                    $data['promotion_type']='2';//分红人角色:1=合伙人,2=空间,3=中心
                    $data['promotion_id']=$value['id'];
                    $data['to_store_id']=$value['pid'];
                    $data['start_time']=$starttime;
                    $data['end_time']=$endtime;
                    $data['lirun']=$lirun_pt;
                    $data['rate']=$value['fh_rate'];
                    $data['price']=$price;
                    $data['count']=$usercount;
                    $data['addtime']=time();
                    $data['bonus_type']=$bonus_type;
                    $data['remark']=$value['fh_remark'];
                    $insertdata[]=$data;

                    
                }
            }
            else
            {
                exit('无需发放');
            }
            if($insertdata)
            {
                $result=db('order_bonus')->insertAll($insertdata);
                if($result)
                {
                    exit('发放成功');
                }
            }
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        exit('发放脚本执行完成');
    }
}
